package com.example.compose

import android.net.Uri
import android.webkit.MimeTypeMap
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.compose.retrofit.NetWorkManager
import com.example.compose.retrofit.entity.LastUpdate
import com.example.compose.retrofit.entity.Reply
import com.example.compose.retrofit.updataApp.DownloadBuild
import com.example.compose.utils.LogUtil
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream


class TestViewModel: ViewModel(),Callback<Reply<LastUpdate>> {
     val test = MutableStateFlow(Reply<LastUpdate>(0,null))

     init {
          NetWorkManager.getRequest()
               .getLastUpdate("com.wifiled.ipixels", "Android")
               .enqueue(this)
     }

     override fun onResponse(call: Call<Reply<LastUpdate>>, response: Response<Reply<LastUpdate>>) {
          viewModelScope.launch {
               val body = response.body() ?: Reply<LastUpdate>(0,null)
               test.value = body
          }
     }

     override fun onFailure(call: Call<Reply<LastUpdate>>, t: Throwable) {
          LogUtil.e("${t.message}")
     }

//     fun download(url: String, build: DownloadBuild) = flow{
//          val response = NetWorkManager.getRequest().downloadFile(url)
//
//          response.body()?.let { body ->
//               val length = body.contentLength()
//               val contentType = body.contentType().toString()
//               val ios = body.byteStream()
//               val info = try {
//                    downloadBuildToOutputStream(build, contentType)
//               } catch(e:Exception){
//                    emit(DownloadStatus.DownloadError(e))
//                    DownloadInfo(null)
//                    return@flow
//               }
//               val ops = info.ops
//               if (ops == null) {
//                    emit(DownloadStatus.DownloadError(RuntimeException("下载出错")))
//                    return@flow
//               }
//               //下载的长度
//               var currentLength: Int = 0
//               //写入文件
//               val bufferSize = 1024 * 8
//               val buffer = ByteArray(bufferSize)
//               val bufferedInputStream = BufferedInputStream(ios, bufferSize)
//               var readLength: Int = 0
//               while (bufferedInputStream.read(buffer, 0, bufferSize)
//                         .also { readLength = it } != -1
//               ) {
//                    ops.write(buffer, 0, readLength)
//                    currentLength += readLength
//                    emit(
//                         DownloadStatus.DownloadProcess(
//                              currentLength.toLong(),
//                              length,
//                              currentLength.toFloat() / length.toFloat()
//                         )
//                    )
//               }
//               bufferedInputStream.close()
//               ops.close()
//               ios.close()
//               if (info.uri != null)
//                    emit(DownloadStatus.DownloadSuccess(info.uri))
//               else emit(DownloadStatus.DownloadSuccess(Uri.fromFile(info.file)))
//
//          } ?: kotlin.run {
//               emit(DownloadStatus.DownloadError(RuntimeException("下载出错")))
//          }
//     }.flowOn(Dispatchers.IO)

     private fun downloadBuildToOutputStream(build: DownloadBuild, contentType: String): DownloadInfo {
          val context = build.getContext()
          val uri = build.getUri(contentType)
          if (build.getDownloadFile() != null) {
               val file = build.getDownloadFile()!!
               return DownloadInfo(FileOutputStream(file), file)
          } else if (uri != null) {
               return DownloadInfo(context.contentResolver.openOutputStream(uri), uri = uri)
          } else {
               val name = build.getFileName()
               val fileName = if(!name.isNullOrBlank()) name else "${System.currentTimeMillis()}.${
                    MimeTypeMap.getSingleton()
                         .getExtensionFromMimeType(contentType)
               }"
               val file = File("${context.filesDir}",fileName)
               return DownloadInfo(FileOutputStream(file), file)
          }
     }

     private class DownloadInfo(val ops: OutputStream?, val file: File? = null, val uri: Uri? = null)

}